<template>
  <admin-layout>
    <div class="riders-view">
      <h2 class="page-title">骑手管理</h2>

      <!-- 搜索区域 -->
      <el-card class="search-card">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="骑手姓名">
            <el-input
              v-model="searchForm.keyword"
              placeholder="请输入骑手姓名"
              clearable
            />
          </el-form-item>

          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 骑手列表 -->
      <el-card class="table-card" v-loading="loading">
        <el-table :data="riderList" border style="width: 100%" row-key="id">
          <el-table-column label="头像" width="80" align="center">
            <template #default="{ row }">
              <el-avatar :size="40" :src="row.avatar || ''">
                {{ row.realName?.substring(0, 1) }}
              </el-avatar>
            </template>
          </el-table-column>

          <el-table-column prop="realName" label="姓名" min-width="100" />

          <el-table-column prop="userId" label="用户ID" min-width="100" />

          <el-table-column prop="vehicleType" label="车辆类型" width="100">
            <template #default="{ row }">
              {{ getVehicleTypeLabel(row.vehicleType) }}
            </template>
          </el-table-column>

          <el-table-column
            prop="vehicleNumber"
            label="车牌号"
            min-width="120"
          />

          <el-table-column prop="status" label="账号状态" width="100">
            <template #default="{ row }">
              <el-tag
                :type="
                  row.status === 'ONLINE'
                    ? 'success'
                    : row.status === 'OFFLINE'
                    ? 'info'
                    : 'danger'
                "
              >
                {{ getStatusLabel(row.status) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="createdAt" label="注册时间" min-width="160">
            <template #default="{ row }">
              {{ formatDate(row.createdAt) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="180" fixed="right">
            <template #default="{ row }">
              <el-button
                size="small"
                type="primary"
                @click="viewRiderDetail(row)"
              >
                查看
              </el-button>
              <el-button
                size="small"
                :type="row.status === 'ONLINE' ? 'danger' : 'success'"
                @click="handleStatusChange(row)"
              >
                {{ row.status === "ONLINE" ? "禁用" : "启用" }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 空状态 -->
        <div v-if="riderList.length === 0 && !loading" class="empty-data">
          暂无骑手数据
        </div>

        <!-- 分页 -->
        <div
          class="pagination-container"
          v-if="pagination.total > 0 || pagination.currentPage > 1"
        >
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            :page-size="pagination.pageSize"
            :current-page="pagination.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            @current-change="handlePageChange"
            @size-change="handleSizeChange"
          />
        </div>
      </el-card>

      <!-- 骑手详情对话框 -->
      <el-dialog
        v-model="detailDialog.visible"
        title="骑手详情"
        width="700px"
        class="rider-detail-dialog"
      >
        <div class="rider-detail" v-if="detailDialog.rider">
          <div class="rider-header">
            <el-avatar
              :size="60"
              :src="detailDialog.rider.avatar || ''"
              class="rider-avatar"
            >
              {{ detailDialog.rider.realName?.substring(0, 1) }}
            </el-avatar>
            <div class="rider-title">
              <h3>{{ detailDialog.rider.realName }}</h3>
              <el-tag
                :type="
                  detailDialog.rider.status === 'ONLINE' ? 'success' : 'danger'
                "
              >
                {{ getStatusLabel(detailDialog.rider.status) }}
              </el-tag>
            </div>
          </div>

          <el-descriptions :column="2" border class="mt-4">
            <el-descriptions-item label="用户ID">
              {{ detailDialog.rider.userId }}
            </el-descriptions-item>
            <el-descriptions-item label="车辆类型">
              {{ getVehicleTypeLabel(detailDialog.rider.vehicleType) }}
            </el-descriptions-item>
            <el-descriptions-item label="车牌号">
              {{ detailDialog.rider.vehicleNumber }}
            </el-descriptions-item>
            <el-descriptions-item label="注册时间">
              {{ formatDate(detailDialog.rider.createdAt) }}
            </el-descriptions-item>
            <el-descriptions-item label="经度">
              {{ detailDialog.rider.longitude }}
            </el-descriptions-item>
            <el-descriptions-item label="纬度">
              {{ detailDialog.rider.latitude }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </el-dialog>
    </div>
  </admin-layout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import AdminLayout from "@/components/admin/AdminLayout.vue";
import { getRiders, updateRiderStatus } from "@/api";

// 状态选项
const statusOptions = [
  { value: "ONLINE", label: "在线" },
  { value: "OFFLINE", label: "离线" },
  { value: "SUSPENDED", label: "已禁用" },
];

// 定义骑手接口
interface Rider {
  id: number;
  userId: number;
  realName: string;
  vehicleType: string;
  vehicleNumber: string;
  status: string;
  longitude: number;
  latitude: number;
  createdAt: string;
  avatar?: string;
}

// 骑手列表
const riderList = ref<Rider[]>([]);
const loading = ref(false);

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 搜索表单
const searchForm = reactive({
  keyword: "", // 关键词 (姓名)
  status: "", // 骑手状态
});

// 详情对话框
const detailDialog = reactive({
  visible: false,
  rider: null as Rider | null,
});

// 获取骑手列表
const fetchRiders = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      status: searchForm.status || undefined,
      keyword: searchForm.keyword || undefined,
    };

    console.log("正在请求骑手数据，参数:", params);
    const res = await getRiders(params);
    console.log("getRiders API响应完整数据:", res);

    const data = res.data?.data || res.data;
    console.log("解析后的数据:", data);

    if (data) {
      // 使用API文档中定义的分页格式
      if (data.content && typeof data.totalElements === "number") {
        riderList.value = data.content;
        pagination.total = data.totalElements;
      } else if (data.list && typeof data.total === "number") {
        riderList.value = data.list;
        pagination.total = data.total;
      } else if (Array.isArray(data)) {
        riderList.value = data;
        pagination.total = data.length;
      } else {
        if (pagination.currentPage === 1) {
          riderList.value = [];
          pagination.total = 0;
        } else {
          // 保持总数不变，以便用户可以返回前面的页面
          riderList.value = [];
        }
      }
      console.log("成功获取骑手数据:", riderList.value);
    } else {
      console.warn("API返回数据为空或格式不正确");
      if (pagination.currentPage === 1) {
        riderList.value = [];
        pagination.total = 0;
      } else {
        // 保持总数不变，以便用户可以返回前面的页面
        riderList.value = [];
      }
    }
  } catch (error) {
    console.error("获取骑手列表失败:", error);
    ElMessage.error("获取骑手列表失败，请检查网络连接或API状态");
    if (pagination.currentPage === 1) {
      riderList.value = [];
      pagination.total = 0;
    } else {
      // 保持总数不变，以便用户可以返回前面的页面
      riderList.value = [];
    }
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchRiders();
};

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = "";
  searchForm.status = "";
  pagination.currentPage = 1;
  fetchRiders();
};

// 处理页面变化
const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchRiders();
};

// 处理每页条数变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchRiders();
};

// 查看骑手详情
const viewRiderDetail = (rider: Rider) => {
  detailDialog.rider = { ...rider };
  detailDialog.visible = true;
};

// 处理状态变更
const handleStatusChange = async (rider: Rider) => {
  const newStatus = rider.status === "ONLINE" ? "SUSPENDED" : "ONLINE";
  const actionText = newStatus === "ONLINE" ? "启用" : "禁用";
  let reason = "";

  if (newStatus === "SUSPENDED") {
    // 如果是禁用操作，可以添加禁用原因
    reason = "管理员禁用";
  }

  try {
    await ElMessageBox.confirm(
      `确定要${actionText}骑手 ${rider.realName} 吗？`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    // 使用API文档中的格式发送请求
    const status = newStatus === "ONLINE" ? "APPROVED" : "SUSPENDED";
    await updateRiderStatus(rider.id.toString(), status, reason);

    ElMessage.success(`${actionText}骑手成功`);

    // 更新本地数据
    rider.status = newStatus;
  } catch (error) {
    if (error !== "cancel") {
      console.error(`${actionText}骑手失败`, error);
      ElMessage.error(`${actionText}骑手失败，请重试`);
    }
  }
};

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return "";
  const date = new Date(dateString);
  return date.toLocaleString();
};

// 获取状态标签
const getStatusLabel = (status: string): string => {
  const statusMap: Record<string, string> = {
    ONLINE: "在线",
    OFFLINE: "离线",
    SUSPENDED: "已禁用",
  };
  return statusMap[status] || status;
};

// 获取车辆类型标签
const getVehicleTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    bike: "自行车",
    electric: "电动车",
    motorcycle: "摩托车",
  };
  return typeMap[type] || type;
};

onMounted(() => {
  fetchRiders();
});
</script>

<style scoped>
.riders-view {
  width: 100%;
}

.page-title {
  margin-bottom: 20px;
  color: var(--primary-dark);
  font-size: 1.5rem;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.table-card {
  min-height: 400px;
}

.empty-data {
  text-align: center;
  padding: 30px 0;
  color: var(--text-secondary);
  font-size: 14px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.rider-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.rider-avatar {
  margin-right: 20px;
}

.rider-title {
  display: flex;
  flex-direction: column;
}

.rider-title h3 {
  margin: 0 0 10px 0;
  font-size: 18px;
}

.mt-2 {
  margin-top: 8px;
}

.mt-4 {
  margin-top: 16px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: var(--primary-dark);
}

.stat-label {
  font-size: 14px;
  color: var(--text-secondary);
  margin-top: 5px;
}
</style>
